const LoginModel = require('../../model/user/login/index')
const ResgisterModel = require('../../model/user/resgister/index')
const VerifyUserNameModel = require('../../model/user/resgister/verifyUserName')
const VerifyPhoneModel = require('../../model/user/resgister/verifyPhone')
const UserInfoModel = require('../../model/user/info/index')
const UserInfoByIdModel = require('../../model/user/info/select-by-id/index')
// 引入jwt生成随机token
const jwt = require('jsonwebtoken');
// 设置token的密钥
const secretKey = 'heartTalk';

const user = {
    // 登录逻辑
    login: async (req, res) => {
        // 重写响应头，并且状态码是200，数据类型是utf-8
        // res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
        // 获取前端的数据
        const {userID, username, password, phone} = req.body
        // 调用model处理数据库逻辑
        await LoginModel({username, password, phone}).then(data => {
            // 有结果
            // console.log(data)
            setTimeout(()=>{
                if (data) {
                    // 生成令牌
                    const payload = {
                        userId: userID,
                        userName: username
                    };
                    const options = {
                        expiresIn: '1h' // 设置有效期为一个小时
                    };
                    const token = jwt.sign(payload, secretKey, options);
                    // console.log('data-->', data)
                    res.returnMsg({token: token, userName: username, userId: userID}, '登录成功', 200)
                }
                // 无结果
                else {
                    console.log(12)
                    // console.log(222)
                    res.returnMsg(null, '账号或密码错误', 500)
                }
            },100)
        }).catch(err => {
            console.log(err)
            res.returnMsg(null, '账号或密码错误', 500)
        })
    },

    // 注册逻辑
    resgister: async (req, res) => {
        const {userName, password, phone, securityCode} = req.body
        // 判断校验值
        let flag = true
        // 校验用户名重复
        await VerifyUserNameModel({userName}).then(data => {
            if (data.length) {
                res.returnMsg(null, '用户名重复', 500)
                flag = false
                return
            } else {
                flag = true
            }
        })
        if (!flag) return;
        // 校验手机号码重复
        await VerifyPhoneModel({phone}).then(data => {
            if (data.length) {
                res.returnMsg(null, '手机号码重复', 500)
                flag = false
                return
            } else {
                flag = true
            }
        })
        if (!flag) return;
        // 校验验证码
        if (securityCode != 123456) {
            res.returnMsg(null, '验证码错误', 500)
            return
        }
        await ResgisterModel({userName, password, phone}).then(data => {
            console.log(data)
            if (data.affectedRows == 1) {
                res.returnMsg(null, '注册成功', 200)
            } else {
                res.returnMsg(null, '注册失败', 500)
            }
        }).catch(err => {
            res.returnMsg(null, err, 500)
        })
    },

    // 查询用户信息
    info: async (req, res) =>{
        const {userName} = req.query
        await UserInfoModel(userName).then(data =>{
            if(data.length){
                res.returnMsg({userId: data[0].userID, phone: data[0].phone}, '查询成功', 200)
            }else{
                res.returnMsg(null, '系统错误或用户不存在', 500)
            }
        })
    },

    // 查询用户信息-根据userID查询
    infoByUserID: async (req, res) =>{
        const userID = req.query.userID
        await UserInfoByIdModel(userID).then(data =>{
            if(data.length){
                res.returnMsg({list: data}, '查询成功', 200)
            }else{
                res.returnMsg(null, '系统错误或用户不存在', 500)
            }
        })
    },
}

module.exports = user;